<?php

require_once "ModelBase.php";
class Event extends TTEvent_Table_Abstract
{
	protected $_name = 'tamtay_event';
	protected $_primary = 'eid';
	
	public function getDetail($eid){
		static $s_events;
		if(is_null($s_events)){
			$s_events = array();
		}
		else if(isset($s_events[$eid]) && $s_events[$eid])
			return $s_events[$eid];
		$sql = "SELECT e.*, t.tid, t.name AS category_name, nw.name as network_name, nt1.name as country_name, nt2.name as city_name, nt3.name as dictrict_name " .
			"FROM tamtay_event e 
			INNER JOIN tamtay_term t ON e.cid=t.tid 
			INNER JOIN mytt_network nw ON e.network_id=nw.nwid " .
			"LEFT JOIN nations nt1 ON e.country=nt1.nid " .
			"LEFT JOIN cities nt2 ON e.city=nt2.cid " .
			"LEFT JOIN districts nt3 ON e.district=nt3.did " .
			"WHERE e.eid=?";
		$db = $this->getSlaveDB();
		$rs = $db->query($sql, $eid);
		$row = $rs->fetch();
		$s_events[$eid] = $row;
		
		return $row;
	}
	
	public function getDetailByShortcut($shortcut){
		static $s_events_byshortcut;
		if(is_null($s_events_byshortcut)){
			$s_events_byshortcut = array();
		}
		else if(isset($s_events_byshortcut[$shortcut]) && $s_events_byshortcut[$shortcut])
			return $s_events_byshortcut[$shortcut];
		$sql = "SELECT e.*, t.tid, t.name AS category_name, nw.name as network_name, nt1.name as country_name, nt2.name as city_name, nt3.name as dictrict_name " .
			"FROM tamtay_event e 
			INNER JOIN tamtay_term t ON e.cid=t.tid 
			INNER JOIN mytt_network nw ON e.network_id=nw.nwid " .
			"LEFT JOIN nations nt1 ON e.country=nt1.nid " .
			"LEFT JOIN cities nt2 ON e.city=nt2.cid " .
			"LEFT JOIN districts nt3 ON e.district=nt3.did " .
			"WHERE e.short_cut=?";
		$db = $this->getSlaveDB();
		$rs = $db->query($sql, $shortcut);
		$row = $rs->fetch();
		$s_events_byshortcut[$shortcut] = $row;
		
		return $row;
	}
	
	public function get($eid){
		static $terms;
		if(is_null($terms)){
			$terms = array();
		}
		else if(isset($terms[$tid]) && $terms[$tid])
			return $terms[$tid];
		$sql = "SELECT * FROM tamtay_event WHERE eid=?";
		$db = $this->getSlaveDB();
		$rs = $db->query($sql, $eid);
		$row = $rs->fetch();
		$terms[$eid] = $row;
		
		return $row;
	}
	
	public function save($item){
		$status = 1;//insert
		if(is_object($item))
			$item = objectToArray($item);
		$eid = $item['eid'];
		unset($item['eid']);
		
		if($this->exists($eid)){
			$item['changed'] = time();
            //va
            $item['published']=0;
            //va
			$this->update($item, 'eid='.$eid);
			return $eid;
		}
		else{
			$this->insert($item);
			$item['created'] = time();
			$item['changed'] = time();
			return $this->_db->lastInsertId();
		}
	}
	
	public function exists($eid){
		$eid = (int)$eid;
		if(!$eid){
			return false;
		}
		$sql = "SELECT eid FROM tamtay_event WHERE eid=".$eid;
		if($this->execScalar($sql))
			return true;
		return false;			
		
	}
	
	public function getHotList($page=0, $limit=20){
		$limit = (int)$limit;
		//$sql = "SELECT * FROM tamtay_event WHERE promote=1 ORDER BY start_time DESC, end_time DESC";
		//va
        $a=getdate();
        $sql = "SELECT * FROM tamtay_event WHERE promote >3 or(end_time_promote>".mktime(0,0,0,$a['mon'],$a['mday'],$a['year'])." and promote != 0 ) ORDER BY start_time DESC, end_time DESC";
        //va
        $this->setRowPerPage($limit);
		return $this->pageQuery($sql, array(), $page);
	}
	
	public function getLastestList($limit=20){
		$limit = (int)$limit;
		$sql = "SELECT * FROM tamtay_event ORDER BY created DESC LIMIT 0,".$limit;
		return $this->execSelectQuery($sql);
	}
	
	public function getListByCategory($cid, $p, $city, $page=0, $limit=20){
		$cid = (int)$cid;
		$sql = "SELECT e.*, t.tid, t.name AS category_name, nw.name as network_name, nt1.name as country_name, nt2.name as city_name, nt3.name as dictrict_name " .
			"FROM tamtay_event e 
			INNER JOIN tamtay_term t ON e.cid=t.tid 
			INNER JOIN mytt_network nw ON e.network_id=nw.nwid " .
			"LEFT JOIN nations nt1 ON e.country=nt1.nid " .
			"LEFT JOIN cities nt2 ON e.city=nt2.cid " .
			"LEFT JOIN districts nt3 ON e.district=nt3.did ";
			
		$where = "";
		if($cid>0){
			$where = "e.cid=$cid";
		}
		if($p>0){
			$where .= ($where!=""?" AND ":"")."e.promote=".($p-1);
		}
		if($city>0){
			$where .= ($where!=""?" AND ":"")."e.city=$city";
		}
		$sql = $sql.($where!=""?" WHERE ":"").$where;
		//var_dump($sql);exit();
		$this->setRowPerPage($limit);
		return $this->pageQuery($sql, array(), $page);
	}
	
	public function getNetworkEvent($nwid, $page=0, $limit=20){
		$from = $page*$limit;
		$nwid = (int)$nwid;
		$sql = "SELECT eid, event_name as name, uid, cid, network_id as nwid, logo, banner, start_time, end_time, address, website, member_count, promote, access, created, changed  FROM tamtay_event WHERE network_id =".$nwid." LIMIT $from, $limit";
		return $this->execSelectQuery($sql);
	}
	
	public function getNetworkEventCount($nwid){
		$nwid = (int)$nwid;
		$sql = "SELECT COUNT(*)  FROM tamtay_event WHERE network_id=".$nwid;
		$db = $this->getSlaveDB();
		return $db->fetchOne($sql);
		
	}
	
	public function destroyEvent($eid){
		$eid=(int)$eid;
		$sql = "DELETE FROM tamtay_event WHERE eid=?";
		$db = $this->getMasterDB();
		return $db->query($sql, $eid);
	}
	
	public function updateStatistic($uid, $total=0){
		$total = (int)$total;
		if($total){
			$sql = "UPDATE statistic SET count_event=? WHERE uid=?";
			$db = $this->getMasterDB();
			$db->query($sql, array($total, $uid));
		}
		
	}
	
	public function search($searchCond, $page=0, $limit=20){
		$page = (int)$page;
		$limit = (int)$limit;
		
		$sql = "SELECT e.*, t.tid, t.name AS category_name, nw.name as network_name, nt1.name as country_name, nt2.name as city_name, nt3.name as dictrict_name " .
			"FROM tamtay_event e 
			INNER JOIN tamtay_term t ON e.cid=t.tid 
			INNER JOIN mytt_network nw ON e.network_id=nw.nwid " .
			"LEFT JOIN nations nt1 ON e.country=nt1.nid " .
			"LEFT JOIN cities nt2 ON e.city=nt2.cid " .
			"LEFT JOIN districts nt3 ON e.district=nt3.did ";
		
		$sqlCount = "SELECT COUNT(e.eid)
			FROM tamtay_event e 
			INNER JOIN tamtay_term t ON e.cid=t.tid 
			INNER JOIN mytt_network nw ON e.network_id=nw.nwid ";
		
		//$where = "";
        //va
        $where="e.published!=0 AND e.promote !=".EVENT_PROMOTE_NOTPUBLISHED;
        //va
		$varArr = array();
	/*va	if(isset($searchCond['p']) && $searchCond['p']!=""){
			$where = $where.($where==""?"":" AND ")."e.promote=".($searchCond['p']-1);
		}*/
        if(isset($searchCond['public']) && $searchCond['public']>0){
            $where = $where.($where==""?"":" AND ")."e.public=? ";
            $varArr[] = $searchCond['public'];
        }
		if(isset($searchCond['keyword']) && $searchCond['keyword']!=""){
			//$where = "(e.event_name LIKE '%?%' OR e.slogan LIKE '%?%' OR e.description LIKE '%?%' ) ";
			//$varArr[] = $searchCond['keyword'];
			//$varArr[] = $searchCond['keyword'];
			//$varArr[] = $searchCond['keyword'];
			$where = $where.($where==""?"":" AND ")."(e.event_name LIKE '%".$searchCond['keyword']."%' OR e.slogan LIKE '%".$searchCond['keyword']."%' OR e.description LIKE '%".$searchCond['keyword']."%' ) ";
		}
		if(isset($searchCond['nwid']) && $searchCond['nwid']>0){
			$where = $where.($where==""?"":" AND ")."nw.nwid=? ";
			$varArr[] = $searchCond['nwid'];
		}
		if(isset($searchCond['cid']) && $searchCond['cid']>0){
			$where = $where.($where==""?"":" AND ")."t.tid=? ";
			$varArr[] = $searchCond['cid'];
		}
		if(isset($searchCond['start_time']) && $searchCond['start_time']!=""){
			list($day, $month, $year) = explode("/", $searchCond['start_time']);
			$start_time = strtotime($year."/".$month."/".$day);
			$where = $where.($where==""?"":" AND ")."(e.end_time > ? ";
			$varArr[] = $start_time;
			
			if(isset($searchCond['end_time']) && $searchCond['end_time']!=""){
				list($day, $month, $year) = explode("/", $searchCond['end_time']);
				$end_time = strtotime($year."/".$month."/".$day." 23:59:59");
				$where = $where.($where==""?"":" AND ")."e.start_time <= ? ";
				$varArr[] = $end_time;
			}
			$where = $where.")";
		}
		else if(isset($searchCond['end_time']) && $searchCond['end_time']!=""){
				list($day, $month, $year) = explode("/", $searchCond['end_time']);
				$end_time = strtotime($year."/".$month."/".$day." 23:59:59");
				$where = $where.($where==""?"":" AND ")."e.start_time <= ? ";
				$varArr[] = $end_time;
			}
		
		$sql = $sql.(!$where?"":" WHERE $where");
		$sqlCount = $sqlCount.(!$where?"":" WHERE $where");
		//var_dump(array($sqlCount, $varArr));exit();
		$db = $this->getSlaveDB();
		if($limit){
			$this->setRowPerPage($limit);
		}
		return $this->pageQuery($sql, $varArr, $page, $sqlCount);
		
	}
	
	public function updateEvent($eid, $Opts){
		$eid = (int)$eid;
		$vals = array();
		if($eid && is_array($Opts) && count($Opts)>0){
			$keys = array_keys($Opts);
			$set = "";
			foreach ($keys as $key){
				$set = $set.($set!=""?", ":"").$key."=?";
				$vals[] = $Opts[$key];
			}
		}
		$sql = "UPDATE tamtay_event SET $set WHERE eid=?";
		$vals[] = $eid;
		
		$db = $this->getMasterDB();
		return $db->query($sql, $vals);
	}

	public function changePromote($eid){
		$sql = "UPDATE tamtay_event SET promote=1-promote WHERE eid=?";
		
		$db = $this->getMasterDB();
		$db->query($sql, $eid);
	}
    
    //va
    public function getTcoin($uid){
        $sql="SELECT tcoin FROM tt_tcoin WHERE uid=?";
        $db = $this->getMasterDB();
        return $db->fetchOne($sql,$uid);
    }
    public function getEndTimePromote($eid){
        $sql="SELECT end_time_promote FROM tamtay_event where eid=?";
        $db = $this->getMasterDB();
        return $db->fetchOne($sql,Array($eid));
    }
    
    public function setEndTimePromote($eid,$end_time_promote){
        $sql="UPDATE  tamtay_event SET  end_time_promote =? WHERE  eid=?";
        $db = $this->getMasterDB();
        $db->query($sql,Array($end_time_promote,$eid));
    }
    public function update_tt_tcoin_log($uid,$eid,$timestamp,$unit_price,$quantity){
        $sql="INSERT INTO  tt_tcoin_log(uid ,
            eid ,
            timestamp ,
            unit_price ,
            quantity
            )
            VALUES (
            ?,?,?,?,?
            )";
        $db = $this->getMasterDB();
        $db->query($sql,Array($uid,$eid,$timestamp,$unit_price,$quantity));
    }
    
    public function updateTcoin($uid,$quantity)
    {
        $sql="UPDATE tt_tcoin SET tcoin=tcoin-? WHERE uid=?";
        $db = $this->getMasterDB();
        $db->query($sql,Array($quantity,$uid));
    }
    public function changePromote2($eid,$value){
        $sql = "UPDATE tamtay_event SET promote=? WHERE eid=?";
        $db = $this->getMasterDB();
        $db->query($sql,Array($value,$eid));
        }
    public function getPromote($eid){
        $sql="SELECT promote FROM tamtay_event WHERe eid=?";
        $db = $this->getMasterDB();
        return $db->fetchOne($sql,$eid);
    }
   
   public function getFocusEvent($limit){
        $db = $this->getMasterDB(); 
        $sql = "SELECT e.*,ct.name AS city_name FROM tamtay_event e INNER JOIN cities ct ON e.city = ct.cid WHERE e.promote=".EVENT_PROMOTE_FOCUS." AND e.published!=0 ORDER BY e.admin_event_changed DESC limit 0,".$limit;
        return $db->fetchAll($sql);
   }
   public function getVipList($limit){

    //    $a=getdate();
   //     $sql = "SELECT * FROM tamtay_event WHERE promote=".EVENT_PROMOTE_VIP." and end_time_promote>".mktime(0,0,0,$a['mon'],$a['mday'],$a['year'])." ORDER BY end_time_promote DESC";
        //$sql="SELECT e.* FROM tamtay_event e INNER JOIN tt_tcoin_log l ON e.eid=l.eid  GROUP BY e.eid HAVING e.promote>0 AND e.end_time_promote >".mktime(0,0,0,$a['mon'],$a['mday'],$a['year'])."  ORDER BY sum(l.quantity) DESC LIMIT ".$page*$limit.",".$limit;
     //   $this->setRowPerPage($limit);
        $sql="SELECT e.*,ct.name AS city_name FROM tamtay_event e INNER JOIN cities ct ON e.city = ct.cid WHERE e.end_time_promote >".time()." AND e.promote >=1 AND e.published!=0 ORDER BY e.total_tcoin DESC limit 0,".$limit;
      //  return $this->pageQuery($sql, array(), $page);
        $db = $this->getMasterDB();
        return $db->fetchAll($sql); 
   }
   public function getHotList2($limit){
        $db = $this->getMasterDB(); 
        $sql = "SELECT e.*,ct.name AS city_name FROM tamtay_event e INNER JOIN cities ct ON e.city = ct.cid WHERE e.promote=".EVENT_PROMOTE_HOT." AND e.published!=0 ORDER BY e.admin_event_changed DESC limit 0,".$limit;
        return $db->fetchAll($sql);
   }
   public function getListByCategory2($cid, $p, $city, $page=0, $limit=10){
        $cid = (int)$cid;
        $sql = "SELECT e.*, t.tid, t.name AS category_name, nw.name as network_name, nt1.name as country_name, nt2.name as city_name, nt3.name as dictrict_name " .
            "FROM tamtay_event e 
            INNER JOIN tamtay_term t ON e.cid=t.tid 
            INNER JOIN mytt_network nw ON e.network_id=nw.nwid " .
            "LEFT JOIN nations nt1 ON e.country=nt1.nid " .
            "LEFT JOIN cities nt2 ON e.city=nt2.cid " .
            "LEFT JOIN districts nt3 ON e.district=nt3.did ";
            
        $where = "";
        if($cid>0){
            $where = "e.cid=$cid";
        }
        if($p>0){
            $where .= ($where!=""?" AND ":"")."e.promote!=".EVENT_PROMOTE_NOTPUBLISHED." AND e.published !=0 ";    
        }else{
            $where .= ($where!=""?" AND ":"")."e.promote!=".EVENT_PROMOTE_NOTPUBLISHED." AND e.published !=0 "; 
        }
        if($city>0){
            $where .= ($where!=""?" AND ":"")."e.city=$city";
        }
        $sql = $sql.($where!=""?" WHERE ":"").$where;
        //var_dump($sql);exit();
        $this->setRowPerPage($limit);
        return $this->pageQuery($sql, array(), $page);
    }
    public function getNetworkName($network_id){
        $sql="SELECT name FROM mytt_network where nwid=?";
        $db = $this->getMasterDB();
        return $db->fetchONE($sql,$network_id);
        
    }
    public function changeCostEventTicket($eid,$cost,$limit){
        $sql="INSERT INTO tamtay_event_ticket (eid, cost, start_time,end_time, `limit`) VALUES ('".$eid."', '".$cost."', '0', '0', '".$limit."') ON DUPLICATE KEY UPDATE cost='".$cost."',`limit`='".$limit."'";
        $db = $this->getMasterDB();
        $db->query($sql);
    }
    public function getEventTicket($eid){
        $sql="SELECT `cost`,`limit` FROM tamtay_event_ticket WHERE eid=?";
        $db= $this->getMasterDB();
        return $db->fetchRow($sql,Array($eid));
    }
    public function update_total_tcoin($eid,$v){
        $sql = "UPDATE tamtay_event SET total_tcoin=total_tcoin+? WHERE eid=?";   
        $db= $this->getMasterDB();
        return $db->query($sql,Array($v,$eid));
    }
    //va
}

